#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "log.h"
#include "tracelog.h"
#include "db_log.h"

//------------------------------------------------------------------------
//------------------------- COMMON ---------------------------------------
//------------------------------------------------------------------------


void _db_message_handler(bool iserror,int no, const char *msg, const char *proc,int line){
	long msglen;
	long proclen;
	char *s;

	msglen =  msg?strlen(msg):0;
	proclen = proc?strlen(proc):0;

	if ( msglen && (msg[msglen-1] == '\r' || msg[msglen-1]=='\n') ) {
		s=(char *)msg;
		s[msglen-1] = 0;
	}
	
	if ( proclen > 50 ) {
		s=(char *)proc;
		s[50] = 0;
	}

	WCHAR *wmsg = new WCHAR[msglen + 100]; //+100 for extra info
	WCHAR *wobj = new WCHAR[100]; //proclen + line is less then 100 for sure
	

	if ( iserror ){
		swprintf(wmsg, L"SQLErr %u : %hs", no, msg);
	} else {
		swprintf(wmsg, L"SQLInfo   : %hs", msg);
	}
	log(_T("DBG: _db_message_handler: wmsg = %s. \n"), wmsg);

	if ( proclen > 0 ) {
		swprintf(wobj, L"%hs (%u)", proc, line);
	} else {
		swprintf(wobj, L"<SQL> (%u)", line);
	}
	log(_T("DBG: _db_message_handler: wobj = %s. \n"), wobj);

	tracelog_add( iserror?2:4, wobj, wmsg);
	//release memory
	delete [] wobj;
	delete [] wmsg;
	
}


bool _dbms_not_supported(WCHAR *pbDBMS){
	WCHAR wmsg[200]=L"Defined DBMS is not supported:  ";
	swprintf(wmsg,L"Defined pbDBMS=%50s is not supported.",pbDBMS);
	tracelog_add(1, L"tracelog.dll", wmsg);
	return false;
}



extern "C" BOOL __stdcall install_message_callback(WCHAR *pbDBMS,void* con){
	
	if(getBasicMaskSet() || getShowTraceLog()){
		if( !wcsncmp( pbDBMS,L"SYC",3) || !wcsncmp( pbDBMS,L"TRACE SYC",9))
			return install_message_callback_syb( con );

		if( !wcsncmp( pbDBMS,L"MSS",3) || !wcsncmp( pbDBMS,L"TRACE MSS",9))
			return install_message_callback_mss( con ); // no con needed?
		
		return _dbms_not_supported(pbDBMS);
	}
	return false;
}

extern "C" BOOL __stdcall remove_message_callback(WCHAR *pbDBMS,void*con){
	
	if( !wcsncmp( pbDBMS,L"SYC",3) || !wcsncmp( pbDBMS,L"TRACE SYC",9))
		return remove_message_callback_syb( con );

	if( !wcsncmp( pbDBMS,L"MSS",3) || !wcsncmp( pbDBMS,L"TRACE MSS",9))
		return remove_message_callback_mss( con ); // no con needed?
	
	return _dbms_not_supported(pbDBMS);
}



